from pathlib import Path
from shutil import copyfile
from datetime import datetime

# 源文件夹
src_path= Path(r'/var/local/piclab/pic')
# 目标文件夹
dsc_path = Path(r'/home/zhouwei/mdisk/pic')

delete_files = []
add_files = []

src_folder_nums = 0
src_file_nums = 0
for src_folder in src_path.iterdir():
    src_folder_nums += 1
    folder_name = src_folder.name
    dsc_folder = dsc_path / folder_name
    if not dsc_folder.exists():
        dsc_folder.mkdir()
    
    src_files = set()
    for src_file in src_folder.iterdir():
        src_file_nums += 1
        src_files.add(src_file.name)
    
    dsc_files = set()
    for dsc_file in dsc_folder.iterdir():
        dsc_files.add(dsc_file.name)
    
    # 需要从目标路径删除的文件
    for delete_file in dsc_files.difference(src_files):
        old_file = dsc_folder / delete_file
        old_file.unlink()
        delete_files.append(old_file.as_posix())
    
    # 需要复制到目标路径的文件
    for new_file in src_files.difference(dsc_files):
        copyfile(src_folder / new_file, dsc_folder / new_file)
        add_files.append((dsc_folder / new_file).as_posix())


with open(dsc_path / f'sync_logs_{datetime.now().strftime("%Y%m%d_%H%M%S")}.txt', 'w') as f:
    f.write(f'目录数量: {src_folder_nums}, 文件数量: {src_file_nums}\n' )
    
    f.write('新增了以下文件\n')
    for file in add_files:
        f.write(file + '\n')
    
    # 打印被删除的文件
    f.write('删除了以下文件\n')
    for file in delete_files:
        f.write(file + '\n')
